package com.cloudcms.web.controller.cms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.cloudcms.web.annotation.SessionId;
import com.cloudcms.web.entity.Attachments;
import com.cloudcms.web.annotation.SessionAdmin;
import com.cloudcms.web.common.BusinessException;
import com.cloudcms.web.util.Constants;
import com.cloudcms.web.entity.Admin;
import com.cloudcms.web.entity.Archives;
import com.cloudcms.web.common.Result;
import com.cloudcms.web.base.redis.session.template.RedisSessionTemplate;
import com.cloudcms.web.service.CmsService;
import com.cloudcms.web.util.PropertyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/archives")
public class ArchivesController {
    private static Logger logger = LoggerFactory.getLogger(ArchivesController.class);
    /**
     * 注入service
     */
    @Autowired
    private CmsService cmsService;
    @Autowired
    private Environment env;
    @Autowired
    private PropertyConfig propertyConfig;
    @Autowired
    private RedisSessionTemplate session;
    @RequestMapping(value = "/list/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  list(Model model, HttpServletRequest request, HttpServletResponse response, @SessionId String sessionId)throws Exception{
        String id = request.getParameter("id");
        String typeid = request.getParameter("typeid");
        String all = request.getParameter("all");
        String pageno = request.getParameter("pageno");
        String pagesize = request.getParameter("pagesize");
        String status = request.getParameter("status");

        pageno = StringUtils.isEmpty(pageno)?"1":pageno;
        pagesize = StringUtils.isEmpty(pagesize)?"20":pagesize;
        System.out.println(env);
        System.out.println(propertyConfig.getValue(""));
        System.out.println(propertyConfig.getValue("business.upload.rootpath"));
        Archives archives = new Archives();
        archives.setId(id);
        archives.setTypeid(typeid);
        archives.setAll(all);
        archives.setStatus(StringUtils.isEmpty(status)?"1":status);
        archives.setPageno(Integer.parseInt(pageno));
        archives.setPagesize(Integer.parseInt(pagesize));
        //return JSON.toJSONString(cmsService.selectArchives(archives));
        Result result = new Result();
        cmsService.selectArchives(archives);
        result.put("data",cmsService.selectArchives(archives));
        if (!StringUtils.isEmpty(id)){
            Attachments attachments = new Attachments();
            attachments.setAid(id);
            result.put("attachment",cmsService.selectAttachments(attachments));
        }
        DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
        deferredResult.setResult(result.toString());
        return deferredResult;
    }
    @RequestMapping(value = "/list/2.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  list2(Model model, HttpServletRequest request, HttpServletResponse response, @SessionAdmin Admin admin)throws Exception{
        return list(model,request,response,null);
    }
    @RequestMapping(value = "/edit/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  edit(Model model, HttpServletRequest request, HttpServletResponse response, @SessionAdmin Admin admin){
        String id = request.getParameter("id");
        String title  = request.getParameter("title");
        String attachment = request.getParameter("attachment");
        String typeid = request.getParameter("typeid");

        if (StringUtils.isEmpty(typeid)){
            throw  new BusinessException(701L,"栏目typeid不能为空");
        }
        if (StringUtils.isEmpty(title)){
            throw  new BusinessException(702L,"标题title不能为空");
        }
        Archives archives = new Archives();
        archives.setTitle(title);
        archives.setRank(request.getParameter("rank"));
        archives.setKeywords(request.getParameter("keywords"));
        archives.setDescription(request.getParameter("description"));
        archives.setLitpic(request.getParameter("litpic"));
        archives.setBody(request.getParameter("body"));

        archives.setIsrecommend(StringUtils.isEmpty(request.getParameter("isrecommend"))?"0":request.getParameter("isrecommend"));
        archives.setPublishtime(StringUtils.isEmpty(request.getParameter("publishtime"))?null:request.getParameter("publishtime"));
        archives.setExpiretime(StringUtils.isEmpty(request.getParameter("expiretime"))?null:request.getParameter("expiretime"));
        archives.setWriter(request.getParameter("writer"));
        archives.setSource(request.getParameter("source"));
        archives.setStatus(request.getParameter("status"));
        archives.setReservedchar1(request.getParameter("reservedchar1"));
        archives.setReservedchar2(request.getParameter("reservedchar2"));
        archives.setReservedchar3(request.getParameter("reservedchar3"));
        archives.setReservedchar4(request.getParameter("reservedchar4"));
        archives.setReservedchar5(request.getParameter("reservedchar5"));
        archives.setModifyby(admin.getUsername());

        JSONArray list = JSONObject.parseArray(attachment);
        if (StringUtils.isEmpty(id)){
            archives.setTypeid(typeid);
            archives.setCreateby(admin.getUsername());
            cmsService.insertArchives(archives);
            id = archives.getId();
        }else{
            archives.setTypeid(typeid);
            archives.setId(id);
            cmsService.updateArchives(archives);
            String ids = "";
            if(!StringUtils.isEmpty(attachment)&&!"[]".equals(attachment)) {
                Map<String, Object> map = new HashMap<String, Object>();
                for(int i = 0;i<list.size();i++){
                    map = list.getJSONObject(i);
                    if(!StringUtils.isEmpty(map.get("id").toString())){
                        if(StringUtils.isEmpty(ids)){
                            ids=map.get("id").toString();
                        }else{
                            ids+=","+ map.get("id").toString();
                        }
                    }
                }
            }
            Attachments attachments = new Attachments();
            attachments.setAid(id);
            attachments.setId(ids);
            cmsService.deleteAttachments(attachments);
        }
        if(!StringUtils.isEmpty(attachment)&&!"[]".equals(attachment)) {
            Map<String, Object> map = new HashMap<String, Object>();
            for(int i = 0;i<list.size();i++){
                map = list.getJSONObject(i);
                if(StringUtils.isEmpty(map.get("id").toString())){
                    map = list.getJSONObject(i);
                    Attachments attachments = new Attachments();
                    attachments.setAid(id);
                    attachments.setName(map.get("name").toString());
                    attachments.setSize(map.get("size")==null?"":map.get("size").toString());
                    attachments.setExt(map.get("ext")==null?"":map.get("ext").toString());
                    attachments.setUrl(map.get("url").toString());
                    attachments.setCreateby("admin");
                    cmsService.insertAttachments(attachments);
                }
            }
        }

        Result result = new Result();
        DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
        deferredResult.setResult(result.toString());
        return deferredResult;
    }
    @RequestMapping(value = "/recommend/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  recommend(Model model, HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");

        if (StringUtils.isEmpty(id)){
            throw  new BusinessException(701L,"文章id不能为空");
        }
        if (StringUtils.isEmpty(request.getParameter("isrecommend"))){
            throw  new BusinessException(701L,"isrecommend不能为空");
        }
        Archives archives = new Archives();
        archives.setId(id);
        archives.setIsrecommend(request.getParameter("isrecommend"));

        cmsService.updateArchives(archives);
        Result result = new Result();
        DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
        deferredResult.setResult(result.toString());
        return deferredResult;
    }
    @RequestMapping(value = "/delete/1.0", method = { RequestMethod.GET, RequestMethod.POST })
    public DeferredResult<String>  delete(Model model, HttpServletRequest request, HttpServletResponse response,@SessionAdmin Admin admin){
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)){
            throw new BusinessException(701L,"文章id不能为空");
        }
        Archives archives = new Archives();
        archives.setId(id);
        archives.setStatus("-1");
        cmsService.updateArchives(archives);
        Result result = new Result();
        DeferredResult<String> deferredResult = new DeferredResult<String>(Constants.TIMEOUT_VALUE);
        deferredResult.setResult(result.toString());
        return deferredResult;
    }
    @RequestMapping(value = "/testException", method = { RequestMethod.GET, RequestMethod.POST })
    public String testException() throws Exception{
        throw new MissingServletRequestParameterException("name","String");
    }
    @RequestMapping(value = "/testMyException", method = { RequestMethod.GET, RequestMethod.POST })
    public String testMyException() throws BusinessException {
        throw new BusinessException("i am a myException");
    }
    public static void main(String[] args){

    }
}